package com.hdax.dmw.user.api;

import com.hdax.dmw.common.exception.DmwException;
import com.hdax.dmw.common.exception.user.LoginException;
import com.hdax.dmw.dtos.user.LoginDto;
import com.hdax.dmw.user.service.UserLoginService;
import com.hdax.dmw.utils.Result;
import com.hdax.dmw.utils.ResultGenerator;
import com.hdax.dmw.utils.ServiceResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static com.hdax.dmw.utils.ServiceResultEnum.GLOBAL_ERROR;

@RestController
@RequestMapping(path = "/user")
@Slf4j
public class LoginApi {

    @ExceptionHandler(value = {DmwException.class})
    public Result exceptionHandler(DmwException e){
        if(e instanceof LoginException){
            //登录异常
            return ResultGenerator.genErrorResult("1006",e.getMessage());
        }
        return ResultGenerator.genFailResult(GLOBAL_ERROR.getMessage());
    }

    @Autowired
    private UserLoginService loginService;

    @PostMapping(path = "/login")
    public Result<LoginDto> login(
            @RequestBody Map<String, Object> params
            ){
        String phone = (String) params.get("phone");
        String password = (String) params.get("password");

        try {
            Result<LoginDto> result = loginService.login(phone, password);
            return result;
        }catch (DmwException e){
            log.error(e.getMessage());
            throw e;
        }
    }
}
